﻿using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Xml;
using SsoaFramework.Core.Other;

namespace SsoaFramework.Core.Behaviors
{
    class MetadataAddressFixer : IClientMessageInspector 
    {
        private readonly Uri routingServicePath;

        public MetadataAddressFixer(Uri routingServicePath)
        {
            this.routingServicePath = routingServicePath;
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            Log.Instance.Debug("Received metadata from {0}", routingServicePath);
            reply = Fix(reply);
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            Log.Instance.Debug("Request for metadata to {0}",routingServicePath);
            return null;
        }

        Message Fix(Message message)
        {
            MemoryStream ms = new MemoryStream();
            XmlWriter writer = XmlWriter.Create(ms);
            message.WriteMessage(writer);
            writer.Flush();
            ms.Position = 0;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(ms);
            
            ChangeAddress(ref xmlDoc);

            ms = new MemoryStream();
            xmlDoc.Save(ms);
            ms.Position = 0;
            XmlReader reader = XmlReader.Create(ms);
            Message newMessage = Message.CreateMessage(reader, int.MaxValue, message.Version);
            newMessage.Properties.CopyProperties(message.Properties);

            return newMessage;
        }

        void ChangeAddress(ref XmlDocument xmlDoc)
        {
            XmlNodeList serviceList = xmlDoc.GetElementsByTagName("wsdl:service");
            foreach (XmlNode service in serviceList)
            {
                foreach (XmlNode port in service.ChildNodes)
                {
                    foreach (XmlNode portNode in port.ChildNodes)
                    {
                        if (portNode.LocalName == "address")
                        {
                            if (portNode.Attributes != null)
                            {
                                foreach (XmlAttribute attribute in portNode.Attributes)
                                {
                                    if (attribute.Name == "location")
                                    {
                                        Log.Instance.Trace("Replacing in metadata, location service address from:\n\t'{0}' to '{1}'",attribute.Value,routingServicePath.ToString());
                                        attribute.Value = routingServicePath.ToString();
                                    }
                                }
                            }
                        }
                        if (portNode.LocalName == "EndpointReference")
                        {
                            foreach (XmlNode childNode in portNode.ChildNodes)
                            {
                                if (childNode.LocalName == "Address")
                                {
                                    Log.Instance.Trace("Replacing in metadata, endpoint service address from\n\t'{0}' to '{1}'", childNode.InnerText, routingServicePath.ToString());
                                    childNode.InnerText = routingServicePath.ToString();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
